import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/res.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/network/response/BaseResp.dart';
import 'package:huajianshe_app/network/response/ResourceResp.dart';
import 'package:huajianshe_app/pages/main/PostPage.dart';
import 'package:huajianshe_app/pages/user_info/model/UserModel.dart';
import 'package:huajianshe_app/utils/dialog_util.dart';
import 'package:huajianshe_app/utils/toast_utils.dart';
import 'package:huajianshe_app/widget/AvatarWidget.dart';
import 'package:huajianshe_app/widget/RoundedCornerWidget.dart';
import 'package:huajianshe_app/widget/SimpleScrollView.dart';
import 'package:huajianshe_app/widget/SmartButton.dart';
import 'package:huajianshe_app/widget/appbar/CAppBar.dart';
import 'package:huajianshe_app/widget/dialog/SelectMediaBottomSheet.dart';
import 'package:image_picker/image_picker.dart';

import 'ImportFriendsDialog.dart';

// 导入一个成员
class ImportFriendPage extends StatefulWidget {

  final int? circleId;
  final String? importUrl;

  const ImportFriendPage(this.circleId, this.importUrl, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _ImportFriendPageState();
  }
}

class _ImportFriendPageState extends BaseState<ImportFriendPage> {

  var data = Friend();// = HashMap<String, dynamic>();
  MediaFileInfo? avatar;
  final _picker = ImagePicker();
  TextEditingController nameController = TextEditingController();
  TextEditingController mobileController = TextEditingController();
  TextEditingController wechatController = TextEditingController();
  TextEditingController companyController = TextEditingController();
  TextEditingController positionController = TextEditingController();

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    if (t is UploadResp) {
      print('${t.data?.url}');
      if (t.data?.url != null) {
        avatar = MediaFileInfo(t.data!.url!, false, t.data!.id);
        setState(() => {});
      }
    } else if (t is BaseResp) {
      if (t.code == 0) {
        data = Friend();
        setState(() => null);
      }
      Toast.show(t.msg);
    }
  }

  @override
  Widget build(BuildContext context) {
    return
    Scaffold(
      appBar: CAppBar(title: '导入名单', backImgUrl: 'ic_black_arrow', overlayStyle: SystemUiOverlayStyle.dark),
      backgroundColor: C.grayF6,
      body: SimpleScrollView(
        padding: EdgeInsets.only(top: 10, left: 13, right: 13, bottom: 13), children: [
          RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, radius: 13,
              child: Padding(padding: EdgeInsets.all(15),
                  child: Row(children: [
                    InkWell(onTap: () => { chooseAvatar() }, child: AvatarWidget(avatar?.path, 40, 0, 0)),
                    W(10),
                    Expanded(child: TextField(autofocus: false, controller: nameController, focusNode: null,
                        style: TS(14, C.gray1A), maxLength: 6, decoration: new InputDecoration(
                          border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                          counterText: '', hintText: "昵称(必填,最多6字)", hintStyle: TS(14, C.grayC3),)
                    )),
                  ])
              )
          ),
          H(10),
          RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 13,
              child: Row(children: [
                W(15),
                Text('联系电话', style: TS(15, C.gray1A)),
                Expanded(child: TextField(autofocus: false, controller: mobileController, focusNode: null, keyboardType: TextInputType.number,
                    style: TS(14, C.gray1A), maxLength: 11, textDirection: TextDirection.rtl, decoration: new InputDecoration(
                      border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                      counterText: '', hintText: "手机号(必填)", hintStyle: TS(14, C.grayC3), hintTextDirection: TextDirection.rtl,)
                )),
                W(15),
              ])
          ),
          H(10),

          RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 13,
              child: Row(children: [
                W(15),
                Text('微信号', style: TS(15, C.gray1A),),
                Expanded(child: TextField(autofocus: false, controller: wechatController, focusNode: null,
                    style: TS(14, C.gray1A), maxLength: 12, textDirection: TextDirection.rtl, decoration: new InputDecoration(
                      border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                      counterText: '', hintText: "微信号", hintStyle: TS(14, C.grayC3), hintTextDirection: TextDirection.rtl,)
                )),
                W(15),
              ])
          ),
          H(10),
          RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 13,
              child: Row(children: [
                W(15),
                Text('公司名称', style: TS(15, C.gray1A),),
                Expanded(child: TextField(autofocus: false, controller: companyController, focusNode: null,
                    style: TS(14, C.gray1A), maxLength: 12, textDirection: TextDirection.rtl, decoration: new InputDecoration(
                      border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                      counterText: '', hintText: "公司名称", hintStyle: TS(14, C.grayC3), hintTextDirection: TextDirection.rtl,)
                )),
                W(15),
              ])
          ),
          H(10),
          RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 13,
              child: Row(children: [
                W(15),
                Text('所属职位', style: TS(15, C.gray1A),),
                Expanded(child: TextField(autofocus: false, controller: positionController, focusNode: null,
                    style: TS(14, C.gray1A), maxLength: 12, textDirection: TextDirection.rtl, decoration: new InputDecoration(
                      border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                      counterText: '', hintText: "所属职位", hintStyle: TS(14, C.grayC3), hintTextDirection: TextDirection.rtl,)
                )),
                W(15),
              ])
          ),
        H(24),
        Padding(padding: EdgeInsets.symmetric(horizontal: 14),
            child: SmartButton(width: double.infinity, height: 44, radius: 22, text: '确定', textColor: Colors.white,
            fontSize: 15, onPressed: submit,)
        ),
        H(10),
        Padding(padding: EdgeInsets.symmetric(horizontal: 14),
            child: SmartButton(width: double.infinity, height: 44, radius: 22, text: '我要同时导入多个用户', textColor: C.primary, backgroundColor: Colors.transparent,
              fontSize: 15, onPressed: importAll,)
        ),
      ])
    );
  }

  chooseAvatar() {
    showMediaDialog();
  }

  void showMediaDialog() {
    DialogUtil.showBottomDialogV2(context, SelectMediaBottomSheet(
      includeVideo: false,
      onMediaResult: (isVideo, isCamera) {
        onMediaResult(isVideo, isCamera);
      },
    ), radius: 13, margin: EdgeInsets.symmetric(horizontal: 5));
  }

  void onMediaResult(bool isVideo, isCamera) async {
    var source = isCamera ? ImageSource.camera : ImageSource.gallery;
    final pickedFile = await _picker.getImage(source: source);
    if (pickedFile != null) {
      File file = File(pickedFile.path);
      uploadImage(file);
    }
  }

  uploadImage(File image) async {
    final String path = image.path;
    final String filename = path.substring(path.lastIndexOf('/') + 1);
    var file = await MultipartFile.fromFile(path, filename: filename);
    debugPrint('file:${file.filename.toString()}');
    sendReq(Api.uploadPic(), UploadResp(), data: {'file': file});
  }

  submit() {
    data.circleId = widget.circleId;
    data.avatar = avatar?.id;
    data.name = nameController.text;
    if (data.name?.isEmpty == true) {
      Toast.show('请输入昵称');
      return;
    }
    data.mobile = mobileController.text;
    if (data.mobile?.isEmpty == true) {
      Toast.show('请输入手机号');
      return;
    }
    data.wechatNo = wechatController.text;
    data.companyName = companyController.text;
    data.positionName = positionController.text;
    sendReq(Api.importFriend(), BaseResp(), data: data.toJson());
  }

  importAll() {
    showDialog(context: context, builder: (BuildContext context) {
      return ImportFriendsDialog(widget.importUrl);
    });
  }
}